import {
  signIn,
  signOut,
  getMenuInfo
} from '@/api/login'
import Layout from '@/layout';
import {
  routes
} from '@/router/routes.js'

const user = {
  state: {
    userInfo: {},
    routeList: []
  },
  mutations: {
    SET_USER_INFO(state, data) {
      state.userInfo = data
    },
    SET_ROUTE_LIST(state, data) {
      state.routeList = data
    }
  },
  actions: {
    Login({
      commit
    }, content) {
      return new Promise((resolve, reject) => {
        signIn(content).then(res => {
          if (res) {
            sessionStorage.setItem('token', res.token)
            resolve(res)
          }
        })
      })
    },
    GetUserInfo({
      commit,
      dispatch
    }, content) {
      return new Promise((resolve, reject) => {
        getMenuInfo().then(res => {
          if (res) {
            commit('SET_USER_INFO', res)
            let newRoutes = res.map(o => {
              return {
                path: o.menuName ? `/${o.menuName}` : '',
                name: o.description,
                hidden: o.hidden,
                component: Layout,
                redirect: o.menuName ? null : '/home',
                meta: {
                  title: o.description,
                  icon: o.icon
                },
                children: o.children && o.children.length ? createTree(o.menuName, o.children) : []
              }
            })
            function createTree(menuName, menus) {
              return menus.map(o => {
                return {
                  path: menuName ? `/${menuName}/${o.menuName}` : `/${o.menuName}`,
                  name: `${o.description}`,
                  hidden: o.hidden,
                  component: () => import( /* webpackChunkName: "about" */ `@/views/${o.pageUrl}`),
                  meta: {
                    title: o.description,
                    icon: o.icon
                  },
                  children: o.children && o.children.length ? createTree(o.menuName, o.children) : []
                }
              })
            }
            commit('SET_ROUTE_LIST', newRoutes)
            resolve(newRoutes)
          } else {
            sessionStorage.clear()
          }
        })
      })
    },
    LoginOut({
      commit
    }, content) {
      return new Promise((resolve, reject) => {
        signOut(content).then(res => {
          resolve(res)
        })
      })
    }
  }
}

export default user